package com.example.watermark;

import com.example.model.WaterSensor;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * Created with IntelliJ IDEA.
 * ClassName: WaterMarkBoundDemo
 * Package: com.example.watermark
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-07-25
 * Time: 11:59
 */

//水位线生成策略 乱序
public class WaterMarkBoundDemo {

    public static void main(String[] args) throws Exception {
        //创建执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //多并行度下 窗口事件时间取最小
        env.setParallelism(1);

        //获取数据
        SingleOutputStreamOperator<WaterSensor> map = env.socketTextStream("hadoop102", 7777)
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        final String[] s = value.split(" ");
                        return new WaterSensor(s[0], Long.valueOf(s[1]), Integer.valueOf(s[2]));
                    }
                });

        WatermarkStrategy<WaterSensor> watermarkStrategy = WatermarkStrategy
                //乱序时间 参数是这只迟到时间 比如10秒 窗口不关闭 延迟3秒 窗口时间为7秒 13秒的数据来了才关闭计算
                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                //设置时间戳 从数据中获取时间戳
                .withTimestampAssigner(new SerializableTimestampAssigner<WaterSensor>() {
                    @Override
                    public long extractTimestamp(WaterSensor element, long recordTimestamp) {
                        return element.getTs() * 1000L;
                    }
                });

        //对输入的数据获取水位线
        //分配时间戳 和 设置水位线
        SingleOutputStreamOperator<WaterSensor> assignTW = map.assignTimestampsAndWatermarks(watermarkStrategy);

        //做KeyBy之后开窗
        SingleOutputStreamOperator<String> process = assignTW.keyBy(value -> value.getId())
                //开窗 设置开窗策略 滚动事件时间窗口
                .window(TumblingEventTimeWindows.of(Time.seconds(10)))
                //设置窗口函数
                //ProcessWindowFunction 输入数据 输出数据 key的类型 窗口的类型
                .process(new ProcessWindowFunction<WaterSensor, String, String, TimeWindow>() {
                    //key的类型 上下文 传进来的数据 采集器
                    @Override
                    public void process(String s, Context context, Iterable<WaterSensor> elements, Collector<String> out) throws Exception {

                        final long start = context.window().getStart();
                        final long end = context.window().getEnd();
                        final String st = DateFormatUtils.format(start, "yyyy-MM-dd HH:mm:ss");
                        String en = DateFormatUtils.format(end, "yyyy-MM-dd HH:mm:ss");

                        //获取条数
                        long l = elements.spliterator().estimateSize();

                        out.collect("key=" + s + " 的窗口的时间[ " + st + "," + en + "] 包含 " + l + "  条数据: " + elements);

                    }
                });

        process.print();
        env.execute();
    }

}
